@file:Suppress("UNCHECKED_CAST")

package com.maodou.core.base

/**
 * UI 状态基接口
 * 定义所有 UI 状态应该具备的基本属性
 */
interface BaseUiState {
    val isLoading: Boolean
    val error: String?
}

/**
 * 通用加载状态
 * 适用于简单的加载场景
 */
data class LoadingUiState(
    override val isLoading: Boolean = false,
    override val error: String? = null
) : BaseUiState

/**
 * 带数据的 UI 状态基类
 * 适用于需要展示数据的场景
 * 
 * @param T 数据类型
 */
data class DataUiState<T>(
    val data: T? = null,
    override val isLoading: Boolean = false,
    override val error: String? = null
) : BaseUiState

/**
 * 列表数据 UI 状态
 * 适用于列表展示场景
 * 
 * @param T 列表项数据类型
 */
data class ListUiState<T>(
    val items: List<T> = emptyList(),
    val isEmpty: Boolean = false,
    override val isLoading: Boolean = false,
    override val error: String? = null,
    val isRefreshing: Boolean = false,
    val isLoadingMore: Boolean = false,
    val hasMore: Boolean = true
) : BaseUiState

/**
 * 分页数据 UI 状态
 * 适用于分页加载场景
 */
data class PagingUiState<T>(
    val items: List<T> = emptyList(),
    val currentPage: Int = 1,
    val totalPages: Int = 0,
    val totalCount: Int = 0,
    override val isLoading: Boolean = false,
    override val error: String? = null,
    val isRefreshing: Boolean = false,
    val isLoadingMore: Boolean = false,
    val hasMore: Boolean = true
) : BaseUiState

/**
 * 表单 UI 状态基类
 * 适用于表单输入场景
 */
data class FormUiState(
    val isValid: Boolean = false,
    val isSubmitting: Boolean = false,
    val submitSuccess: Boolean = false,
    override val isLoading: Boolean = false,
    override val error: String? = null,
    val fieldErrors: Map<String, String> = emptyMap()
) : BaseUiState

/**
 * UI 状态扩展函数
 */

/**
 * 检查是否有错误
 */
fun BaseUiState.hasError(): Boolean = !error.isNullOrBlank()

/**
 * 检查是否为空状态（既不加载也没有错误）
 */
fun BaseUiState.isIdle(): Boolean = !isLoading && !hasError()

/**
 * 创建加载状态
 */
fun <T : BaseUiState> T.withLoading(loading: Boolean = true): T {
    return when (this) {
        is LoadingUiState -> copy(isLoading = loading) as T
        is DataUiState<*> -> copy(isLoading = loading) as T
        is ListUiState<*> -> copy(isLoading = loading) as T
        is PagingUiState<*> -> copy(isLoading = loading) as T
        is FormUiState -> copy(isLoading = loading) as T
        else -> this
    }
}

/**
 * 创建错误状态
 */
fun <T : BaseUiState> T.withError(error: String?): T {
    return when (this) {
        is LoadingUiState -> copy(error = error, isLoading = false) as T
        is DataUiState<*> -> copy(error = error, isLoading = false) as T
        is ListUiState<*> -> copy(error = error, isLoading = false) as T
        is PagingUiState<*> -> copy(error = error, isLoading = false) as T
        is FormUiState -> copy(error = error, isLoading = false) as T
        else -> this
    }
}

/**
 * 清除错误状态
 */
fun <T : BaseUiState> T.clearError(): T {
    return withError(null)
}